<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { CompanyApi } from '#/api/system/company';
import type { UserApi } from '#/api/system/user';

import { nextTick, onMounted, ref } from 'vue';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { Plus } from '@vben/icons';

import { ElButton, ElMessage, ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getCompanyList } from '#/api/system/company';
import { deleteUser, getUserList } from '#/api/system/user';
import { EditInfo } from '#/components/edit-info/index';

import UserBindRoleDrawer from './components/user-bind-role-drawer.vue';
import UserFormDrawer from './components/user-form-drawer.vue';
import { useGridColumns, useGridFormSchema } from './data';

// 公司列表数据（仅用于表格搜索）
const companyList = ref<CompanyApi.Company[]>([]);

// 用户表单抽屉组件
const [UserDrawer, userDrawerApi] = useVbenDrawer({
  connectedComponent: UserFormDrawer,
  destroyOnClose: true,
});

// 角色绑定抽屉组件
const [BindRoleDrawer, bindRoleDrawerApi] = useVbenDrawer({
  connectedComponent: UserBindRoleDrawer,
  destroyOnClose: true,
});

/** 刷新表格 */
function onRefresh() {
  gridApi.query();
}

/** 编辑用户 */
function onEdit(row: UserApi.User) {
  userDrawerApi.setData(row).open();
}

/** 创建用户 */
function onCreate() {
  userDrawerApi.setData(null).open();
}

/** 绑定角色 */
function onBindRole(row: UserApi.User) {
  bindRoleDrawerApi.setData(row).open();
}

/** 删除用户 */
async function onDelete(row: UserApi.User) {
  await ElMessageBox.confirm(`确定要删除用户"${row.userName}"吗？`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  });
  await deleteUser(row.id as number);
  ElMessage.success('删除成功');
  onRefresh();
}

/** 表格操作按钮的回调函数 */
function onActionClick({ code, row }: OnActionClickParams<UserApi.User>) {
  switch (code) {
    case 'bindRole': {
      onBindRole(row);
      break;
    }
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
  }
}

/** 加载公司列表 */
async function loadCompanyList() {
  try {
    const { list } = await getCompanyList({ pageNum: 1, pageSize: 999 });
    companyList.value = list;

    // 更新搜索表单的公司选项
    await gridApi.formApi.updateSchema([
      {
        fieldName: 'companyId',
        label: '所属公司',
        component: 'Select',
        componentProps: {
          placeholder: '请选择公司',
          allowClear: true,
          options: list.map((item) => ({
            label: item.name,
            value: item.id,
          })),
        },
      },
    ]);
  } catch (error) {
    console.error('加载公司列表失败:', error);
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: useGridColumns(onActionClick),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getUserList({
            pageNum: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
    },
  } as VxeTableGridOptions<UserApi.User>,
});

onMounted(async () => {
  // 等待Grid组件初始化完成后再加载公司选项数据
  await nextTick();
  await loadCompanyList();
});
</script>

<template>
  <Page auto-content-height>
    <UserDrawer @success="onRefresh" />
    <BindRoleDrawer @success="onRefresh" />

    <Grid table-title="用户列表">
      <template #edit-info="{ row }">
        <EditInfo :handler-name="row.handlerName" :time="row.updateTime" />
      </template>
      <template #toolbar-tools>
        <ElButton
          type="primary"
          @click="onCreate"
          v-access:code="['system:user:add']"
        >
          <Plus class="mr-2 size-5" />
          新增用户
        </ElButton>
      </template>
    </Grid>
  </Page>
</template>
